<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of CoreApp
 *
 * @author jianfeng
 */
class BSpaceEngine extends BApp {

    //operations

    const LOADSpaceOPERATION = "loadSpace";
    const ADDAppOPERATION = "addApp";
    const GETAppSOPERATION = "getApps";
    const Operation_spaceMessage = "spaceMessage";
    const Operation_manageMember = "manageMember";
    const Message_SpaceMessage = "spaceMessage";
    const Request_JoinService = 'joinService';

    private $operationList = array();

    /*

      protected function init() {
      parent::init();
      $this->setDbAdapter(new BSpaceEngineDb($this));
      }

      public function getAppByOperation($operation) {
      $db = new BSpaceEngineDb();

      $appClass = $db->getAppClassByOperationId($operation);

      $app = new $appClass;

      return $app;
      }
     * 
     */

    /**
     *
     * @param type $BSpace
     * @param type $BApp 
     */
    /*
      public function addApp($config = NULL) {

      //$olineQue = new BOnlineQueue();
      $spaceId = NULL;
      $appId = NULL;

      if ($config != NULL) {
      $space = $config['Space'];
      $app = $config['App'];

      if (is_numeric($space))
      $spaceId = $space;
      if ($space instanceof BSpace)
      $spaceId = $space->getId();

      if (is_numeric($app))
      $appId = $app;
      if ($app instanceof BApp)
      $appId = $app->getId();

      //$db = $this->getDbAdapter();

      if ($spaceId != NULL && $appId != NULL) {
      $app = BApp::getInstanceById($appId);
      $app->addToSpace($spaceId);
      //$dbresult = $db->addApp($spaceId, $appId);
      }

      //$app->addToSpace($space);
      }
      }
     * 
     */

    /*
      protected function getApps($config) {

      $space = $config['Space'];

      return $space->getApps();
      }
     * 
     */

    /*
      protected function getUserApps($config) {
      $userApps = array();
      $user = $config['User'];
      $space = $config['Space'];

      $apps = $this->getApps(array('Space' => $space));

      foreach ($apps as $app) {
      $roles = $app->getAuthManager()->getUserRoles($user, $space);

      if ($roles != null && !empty($roles)) {
      array_push($userApps, $app);
      }
      }

      return $userApps;
      }
     * 
     */

    /*
      public function getSpaceType($spaceId) {

      $db = $this->getDbAdapter();

      $type = $db->getSpaceType($spaceId);

      return $type;
      }
     * 
     */

    /*

      protected function addSpaceMember($spaceId, $roleId, $userId) {
      $authManager = $this->getAuthManager();
      if (is_string($roleId))
      $roleId = $authManager->getRoleId($roleId);
      $result = $authManager->assignUserToRole($spaceId, $userId, $roleId);

      if ($result > 0)
      return TRUE;

      return FALSE;
      }
     * 
     */

    public function getUIManager($style = NULL) {
        if ($this->uiManager == NULL) {
            $this->uiManager = new BUIApp($this);
            //$this->uiManager->setActiveSpace(Blyn::app()->getActiveSpace());
        }
        return $this->uiManager;
    }

    /*
      public function main($data = null) {

      }
     * 
     */

    public function runManageMember($data = NULL) {
        if (yii::app()->request->isAjaxRequest) {
            $updateControl = Blyn::app()->getUIManager()->getUpdateControl();
            $senderControl = Blyn::app()->getUIManager()->getSenderControl();
            $requestItem = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('reqId');
            $requestId = $requestItem['messageId'];
            $roleId = $requestItem['roleId'];
            $userId = $requestItem['userId'];
            $screen = Blyn::app()->getUIManager()->getCurrentScreen();

//            $removeUserRoleId = Blyn::app()->getUIManager()->getCurrentScreen()->getContextVariable('removeUserRoleId');
            if ($requestId != NULL && $senderControl->isAjaxLinkClicked('Remove' . $requestId)) {
                $removeUserRoleId = $requestId; //Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('joinedUserId');
                if ($removeUserRoleId > 0 && $userId > 0) {
                    $data = array('userId' => $userId);
                    Blyn::app()->getCurrentUser()->removeRole($removeUserRoleId, $data);

                    $operation = Blyn::app()->getActiveOperation();
                    $space = $this->getCurrentSpace();
                    $userData = array();
                    //send user a remove message
                    $userData['userId'] = $userId;
                    $userData['name'] = 'manageMember';
//                    $messageModel = new MessageFormModel();
//                    {
//                        $messageModel->id = 0;
                    $receiver = new BUser($userId);
//                        $messageModel->sendTo = $receiver->getName();
//                        $sender_user = Blyn::app()->getCurrentUser()->getName();
                    $sender_Space = $space->getName();
                    $roleToJoin = new BRole($roleId);
//                        $apps = $space->getApps();
//                        $appToJoin = $apps[$roleToJoin->appId];
//                        $appName = $appToJoin->getName();
//                        $data = Yii::t('site', 'Role Removed');
//                        $messageModel->messageBody = 
                    $userData['content'] = $sender_Space . ' ' . Yii::t('site', 'Role') . ' ' . Yii::t('site', $roleToJoin->name) . ' : ' . Yii::t('site', 'Remove');
//                        $operation->getMessenger()->sendMessage($messageModel->messageBody, $messageModel->sendTo, NULL, $data);                        
//                    }
//                    $user = Blyn::app()->getCurrentUser();
//                    $personalApp = $user->getPersonalSpace()->getAppByName('BPersonalApp');
//                    $personalApp->getOperation('manageMember')->getMessenger()->
                    $operation->getMessenger()->sendMessage('manageMember', NULL, $userData);
                }
                $updateControl->addRenderView('processJoinSpaceRequest', 'processJoinSpaceRequest', array('requestId' => $requestId));
            } else if ($requestId != NULL && $senderControl->isAjaxLinkClicked('Reject' . $requestId)) {
                if ($requestId > 0) {
                    if ($roleId > 0)
                        Blyn::app()->getCurrentUser()->rejectMember($roleId);
                    //remove request join space message?
//                    $operation = Blyn::app()->getActiveOperation();
//                    $space = $this->getCurrentSpace();
//                    $operation->getMessenger()->removeJoinSpaceMessage($requestId, $space);
//                    
//                    //send user a reject message
//                    $messageModel = new MessageFormModel();
//                    {
//                        $messageModel->id = 0;
//                        $receiver = new BUser($userId);
//                        $messageModel->sendTo = $receiver->getName();
//                        $sender_user = Blyn::app()->getCurrentUser()->getName();
//                        $sender_Space = $space->getName();
//                        $roleToJoin = new BRole($roleId);
//                        $apps = $space->getApps();
//                        $appToJoin = $apps[$roleToJoin->appId];
//                        $appName = $appToJoin->getName();
//                        $data = Yii::t('site', 'Request Rejected');
//                        $messageModel->messageBody = Yii::t('site', 'Join').' '.$sender_Space.' '.Yii::t('site', $roleToJoin->name).' : '.Yii::t('site', 'Reject');
//                        $operation->getMessenger()->sendMessage($messageModel->messageBody, $messageModel->sendTo, NULL, $data);
//                    }
                    //update messageMeta 
                    $messageTable = new BMessageSheet('message');
                    $messageList = $messageTable->getListById($requestId);
                    $messageNameItem = $messageList->getItem('name');
                    if ($messageNameItem) {
                        $messageName = $messageNameItem->getValue();
                    }

                    if ($messageName === 'applyJoinSpace') {
                        $messageStatusItem = $messageList->getItem('messageStatus');

                        if ($messageStatusItem) {
                            $messageStatus = $messageStatusItem->getValue();

                            if ($messageStatus != 'rejected') {
                                $result = 'rejected';
                                $messageStatusItem->save($result);
                            }
                        } else {
                            $result = 'rejected';
                            $messageList->addItem('messageStatus', $result);
                        }
                    }
                }
                $updateControl->addRenderView('processJoinSpaceRequest', 'processJoinSpaceRequest', array('requestId' => $requestId));
            } else if ($requestId != NULL && $senderControl->isAjaxLinkClicked('Accept' . $requestId)) {
                if ($requestId > 0) {
//                    if ($roleId > 0)
//                        Blyn::app()->getCurrentUser()->acceptMember($roleId, $requestItem);
                    //remove request join space message?
//                    $operation = Blyn::app()->getActiveOperation();
//                    $space = $this->getCurrentSpace();
//                    $operation->getMessenger()->removeJoinSpaceMessage($requestId, $space);
                    //send user a accept message
//                    $messageModel = new MessageFormModel();
//                    {
//                        $messageModel->id = 0;
//                        $receiver = new BUser($userId);
//                        $messageModel->sendTo = $receiver->getName();
//                        $sender_user = Blyn::app()->getCurrentUser()->getName();
//                        $sender_Space = $space->getName();
//                        $roleToJoin = new BRole($roleId);
//                        $apps = $space->getApps();
//                        $appToJoin = $apps[$roleToJoin->appId];
//                        $appName = $appToJoin->getName();
//                        $data = Yii::t('site', 'Request Accepted');
//                        
//                        $messageModel->messageBody = Yii::t('site', 'Join').' '.$sender_Space.' '.Yii::t('site', $roleToJoin->name).' : '.Yii::t('site', 'Accept');
//                        $operation->getMessenger()->sendMessage($messageModel->messageBody, $messageModel->sendTo, NULL, $data);
                    //add role
                    $messageTable = new BMessageSheet('message');
                    $messageList = $messageTable->getListById($requestId);
                    $messageNameItem = $messageList->getItem('name');
                    if ($messageNameItem) {
                        $messageName = $messageNameItem->getValue();
                    }

                    if ($messageName === 'applyJoinSpace') {
                        $messageStatusItem = $messageList->getItem('messageStatus');

                        if ($messageStatusItem) {
                            $messageStatus = $messageStatusItem->getValue();

                            if ($messageStatus != 'approved' && $messageStatus != 'rejected') {
                                $result = 'approved';
                                $messageStatusItem->save($result);
                                $receiver = new BUser($userId);
                                $receiver->addRole($roleId);
                            }
                        } else {
                            $result = 'approved';
                            $messageList->addItem('messageStatus', $result);
                            $receiver = new BUser($userId);
                            $receiver->addRole($roleId);
                        }
                    }
                }
                $updateControl->addRenderView('processJoinSpaceRequest', 'processJoinSpaceRequest', array('requestId' => $requestId));
            }


            /*
              if ($senderControl->isAjaxLinkClicked('adminApplyRole')) {
              $updateControl->addRenderView('adminMemberShip', 'adminMemberShip');
              }
             * 
             */

            $membershipControl = new BUIMembership('membershipRole');
            $roleControl = new BUIRole('roleControl');
            $screen->addChildControl($membershipControl);
            $screen->addChildControl($roleControl);

            if ($senderControl->isAjaxLinkClicked('showMemberList')) {
                $updateControl->addRenderView('processJoinSpaceRequest');
                $screen->removeChildControl('membershipControl');
                $screen->removeChildControl('roleControl');
                //$updateControl->render();
                //Blyn::app()->end();
            }

            if ($senderControl instanceof BUIOperation) {
                $screen->addRenderView('processJoinSpaceRequest');
            }
        }
    }

    public function getAllowJoinSpaceRoles($data = NULL) {

        //$currentSpace = $this->getCurrentSpace();
        //$currentSpace->getConfigManager();
        $space = $this->getCurrentSpace();
        $customerRoles = $space->getSpaceEngine()->getRoles(array('type' => BRole::Role_App_customer), TRUE);
        $retCustomerRoles = array();
        $retAutoJoinRoles = array();
        $autoJoinPermit = BPermit::find(BPermit::Role_Allow_Join . '.' . BPermit::Role_Allow_Auto_Join);

        $userRoles = BRole::findUserRoles();

        foreach ($customerRoles as $id => $role) {
            //by default, customer roles is allowed to auto join
            if (!BPermit::checkResourcePermit($role, BPermit::Role_Not_Auto_Join, $userRoles)) {
                $retAutoJoinRoles[$id] = $role;
                //$retCustomerRoles[$id] = $role;
            } else if (!BPermit::checkResourcePermit($role, BPermit::Role_Not_Allow_Join, $userRoles)) {
                $retCustomerRoles[$id] = $role;
            }
            /*
              if (BPermit::checkResourcePermit($role, $autoJoinPermit, $userRoles)) {
              $retAutoJoinRoles[$id] = $role;
              unset($retCustomerRoles[$id]);
              }
             * 
             */
        }

        $memberRoles = $space->getSpaceEngine()->getRoles(array('type' => BRole::Role_App_Member), TRUE);
        $retMemberRoles = array();

        foreach ($memberRoles as $id => $role) {
            //by default, member roles is allowed to join
            if (!BPermit::checkResourcePermit($role, BPermit::Role_Not_Allow_Join, $userRoles)) {
                $retMemberRoles[$id] = $role;
            }
            if (BPermit::checkResourcePermit($role, $autoJoinPermit, $userRoles)) {
                $retAutoJoinRoles[$id] = $role;
                unset($retMemberRoles[$id]);
            }
        }

        $adminRoles = $space->getSpaceEngine()->getRoles(array('type' => BRole::Role_App_Admin), TRUE);
        $retAdminRoles = array();

        foreach ($adminRoles as $id => $role) {
            //by default, admin roles is not allowed to join
            if (BPermit::checkResourcePermit($role, BPermit::Role_Allow_Join, $userRoles))
                $retAdminRoles[$id] = $role;
            if (BPermit::checkResourcePermit($role, $autoJoinPermit, $userRoles)) {
                $retAutoJoinRoles[$id] = $role;
                unset($retAdminRoles[$id]);
            }
        }

        $allowJoinRoles = array();

        if ($retCustomerRoles != NULL)
            $allowJoinRoles['customerRoles'] = $retCustomerRoles;
        if ($retMemberRoles != NULL)
            $allowJoinRoles['memberRoles'] = $retMemberRoles;
        if ($retAdminRoles != NULL)
            $allowJoinRoles['adminRoles'] = $retAdminRoles;
        if ($retAutoJoinRoles != NULL)
            $allowJoinRoles['autoJoinRoles'] = $retAutoJoinRoles;

        return $allowJoinRoles;
    }

    public function runAppStore($data = NULL) {
        //parent::render($data);
        $model = new AddAppFormModel();

        if (isset($_POST['AddAppFormModel'])) {
            $model->attributes = $_POST['AddAppFormModel'];
        }

        $apps = $this->getAppsData();
        $screen = Blyn::app()->getUIManager()->getCurrentScreen();
        $sender = Blyn::app()->getUIManager()->getSenderControl();
        if (!$sender instanceof BUIControl)
            $sender = $screen;
        foreach ($apps as $id => $name) {
            if ($sender->isAjaxLinkClicked(array('ajaxLinkId' => 'addApp' . $id))) {
                Blyn::app()->getActiveSpace()->addApp($id);
                //$this->addApps(array($id));
                // Blyn::app()->getUIManager()->gotoNode(Blyn::app()->getActiveSpace());
            }
        }
//        $appStoreStr = Yii::t('site','appStore');
//        $this->addRenderView($appStoreStr, 'appStoreView', array('model' => $model));
        //$this->addRenderView('appStore', 'appStoreView', array('model' => $model));
    }

    public function getAppsData() {

        $blynConfigPath = yii::getPathOfAlias('application.application.config') . '/config.php';

        $blynConfig = require $blynConfigPath;

//        $appStoreStr = Yii::t('site','appStore');
//        $configApps = $blynConfig[$appStoreStr]['app_list'];
        $configApps = $blynConfig['appStore']['app_list'];

        $apps = array();
        foreach ($configApps as $appClass => $appConfig) {
            if (class_exists($appClass)) {
                $app = new $appClass();
//                $appGroupRoot = BAppGroup::getRoot();
//                $appTypeGroup = BAppGroup::find('app_type');
//                if(!$appTypeGroup instanceof BAppGroup)
//                    $appTypeGroup = new BAppGroup ();
//                $appTypeGroup->name = 'app_type';
//                $appGroupRoot->addChild($appTypeGroup);
//                
//                $normalApp = BAppGroup::find('app_type_normal');
//                if(!$normalApp instanceof BAppGroup)
//                {
//                    $normalApp = new BAppGroup();
//                $normalApp->name = 'app_type_normal';
//                $appTypeGroup->addChild($normalApp);
//                }
//                $normalApp->addMember($app);

                $apps[$app->getId()] = $app;
            }
        }

        //$space = Blyn::app()->getActiveSpace();
        //$db = Blyn::app()->getAppDb();
        //$apps = $db->getVisibleApps($space);
        $appContext = new BApp();
        $appContext->name = BEntity::String_Any;
        $appContext->className = BEntity::String_Any;

        //$allAppGroup = BAppGroup::find($appContext);
        $apps = BApp::findAll($appContext);

        $myApps = Blyn::app()->getActiveSpace()->getApps();

        $ids = array();

        foreach ($apps as $id => $app) {
            array_push($ids, $id);
        }

        foreach ($myApps as $app) {
            $appId = $app->getId();
//            $parentClass = get_parent_class($app);
//            if($app->getGroup('app_type.app_type_normal') instanceof BAppGroup) {
            if (in_array($appId, $ids)) {
                unset($apps[$appId]);
                //               }
            }
        }

        $data = array();

        foreach ($apps as $app) {
            $appName = get_class($app);
            if ($appName != 'BPersonalApp') {
                $data[$app->getId()] = $app->getName();
            }
        }
        return $data;
    }

    public function addApps($sApps) {
        $spaceId = Blyn::app()->getActiveSpace()->getId();

        foreach ($sApps as $appId) {
            $result = Blyn::app()->getActiveApp()->doOperation(BSpaceEngine::ADDAppOPERATION, array('Space' => $spaceId, 'App' => $appId));
        }
    }

    public function getJoinedSpaceRoles($data = NULL) {

        //$currentSpace = $this->getCurrentSpace();
        //$currentSpace->getConfigManager();
        $loginUserId = Blyn::app()->getCurrentUser()->getId();
        $currentSpace = $this->getCurrentSpace();
        $customerRoles = $currentSpace->getSpaceEngine()->getRoles(array('type' => BRole::Role_App_customer), TRUE);
        $memberRoles = $currentSpace->getSpaceEngine()->getRoles(array('type' => BRole::Role_App_Member), TRUE);

        //get all role_user records
        $allRoleUsers = BMRoleUser::model()->findAll();

        $retJoinedUserRoles = array();

        foreach ($allRoleUsers as $roleUserId => $roleUser) {
            foreach ($customerRoles as $customerRoleId => $role) {
                if ($customerRoleId == $roleUser->role_id) {
//                    array_push($retJoinedUserRoles, array('userId'=>$roleUser->user_id, 
//                        'spaceId'=>$currentSpace->getId(), 'appId'=>$role->appId, 'applyingRole'=>$role->name));
                    $retJoinedUserRoles[$roleUser->_id] = array('roleId' => $roleUser->role_id, 'userId' => $roleUser->user_id,
                        'spaceId' => $currentSpace->getId(), 'appId' => $role->appId, 'applyingRole' => $role->name);
                }
            }
            foreach ($memberRoles as $memberRoleId => $role) {
                if ($memberRoleId == $roleUser->role_id) {
//                    array_push($retJoinedUserRoles, array('userId'=>$roleUser->user_id, 
//                        'spaceId'=>$currentSpace->getId(), 'appId'=>$role->appId, 'applyingRole'=>$role->name));
                    $retJoinedUserRoles[$roleUser->_id] = array('roleId' => $roleUser->role_id, 'userId' => $roleUser->user_id,
                        'spaceId' => $currentSpace->getId(), 'appId' => $role->appId, 'applyingRole' => $role->name);
                }
            }
        }

//        $memberRoles = $currentSpace->getSpaceEngine()->getRoles(array('type' => BRole::Role_App_Member), TRUE);
//        $retMemberRoles = array();
//        $adminRoles = $currentSpace->getSpaceEngine()->getRoles(array('type' => BRole::Role_App_Admin), TRUE);
//        $retAdminRoles = array();

        return $retJoinedUserRoles;
    }

    public function getWXJoinedSpaceRoles($data = NULL) {

        //$currentSpace = $this->getCurrentSpace();
        //$currentSpace->getConfigManager();
        $loginUserId = Blyn::app()->getCurrentUser()->getId();
        $currentSpace = $this->getCurrentSpace();

        $operation = Blyn::app()->getActiveOperation();
        $messageView = $operation->getMessenger()->receiveMessages('processJoinSpace');

        $customerRoles = $currentSpace->getSpaceEngine()->getRoles(array('type' => BRole::Role_App_customer), TRUE);
        $memberRoles = $currentSpace->getSpaceEngine()->getRoles(array('type' => BRole::Role_App_Member), TRUE);

        //get all role_user records
        $allRoleUsers = BMRoleUser::model()->findAll();

        $retJoinedUserRoles = array();

        foreach ($allRoleUsers as $roleUserId => $roleUser) {
            foreach ($customerRoles as $customerRoleId => $role) {
                if ($customerRoleId == $roleUser->role_id) {
//                    array_push($retJoinedUserRoles, array('userId'=>$roleUser->user_id, 
//                        'spaceId'=>$currentSpace->getId(), 'appId'=>$role->appId, 'applyingRole'=>$role->name));
                    $retJoinedUserRoles[$roleUser->_id] = array('roleId' => $roleUser->role_id, 'userId' => $roleUser->user_id,
                        'spaceId' => $currentSpace->getId(), 'appId' => $role->appId, 'applyingRole' => $role->name);
                }
            }
            foreach ($memberRoles as $memberRoleId => $role) {
                if ($memberRoleId == $roleUser->role_id) {
//                    array_push($retJoinedUserRoles, array('userId'=>$roleUser->user_id, 
//                        'spaceId'=>$currentSpace->getId(), 'appId'=>$role->appId, 'applyingRole'=>$role->name));
                    $retJoinedUserRoles[$roleUser->_id] = array('roleId' => $roleUser->role_id, 'userId' => $roleUser->user_id,
                        'spaceId' => $currentSpace->getId(), 'appId' => $role->appId, 'applyingRole' => $role->name);
                }
            }
        }
        return $retJoinedUserRoles;
    }

    public function getWXJoinSpaceRequests($data = NULL) {
        $retJoinedUserRoles = array();
        $currentSpace = $this->getCurrentSpace();
        $operation = Blyn::app()->getActiveOperation();
        $joinSpaceRequests = $operation->getMessenger()->receiveMessages('processJoinSpace');
        $messageUserId = null;
        $messageRoleId = null;

        //parse the message treelist
        $messageTable = new BMessageSheet('message');
        foreach ($joinSpaceRequests as $messageId => $rquestTreelist) {
            $messageList = $messageTable->getListById($messageId);
            $messageNameItem = $messageList->getItem('name');
            if ($messageNameItem) {
                $messageName = $messageNameItem->getValue();
            }
            $messageStatusItem = $messageList->getItem('messageStatus');

            if ($messageStatusItem) {
                $messageStatus = $messageStatusItem->getValue();
            }

            if ($messageName === 'applyJoinSpace' && (!$messageStatusItem ||
                    ($messageStatusItem && $messageStatus != 'rejected' && $messageStatus != 'approved'))) {
                $messageUserIdItem = $messageList->getItem('userId');
                if ($messageUserIdItem) {
                    $messageUserId = $messageUserIdItem->getValue();
                }
                $messageRoleIdItem = $messageList->getItem('roleId');
                if ($messageRoleIdItem) {
                    $messageRoleId = $messageRoleIdItem->getValue();
                }

                if ($messageUserId != null && $messageRoleId != null) {
                    //get request User
                    $roleUser = new BUser($messageUserId);

                    //get operation space & app id
                    $spaceId = $currentSpace->getId();
                    $appId = Blyn::app()->getActiveApp()->getId();

                    $customerRoles = $currentSpace->getSpaceEngine()->getRoles(array('type' => BRole::Role_App_customer), TRUE);
                    foreach ($customerRoles as $customerRoleId => $role) {
                        if ($customerRoleId == $messageRoleId) {
                            $retJoinedUserRoles[$messageId] = array('roleId' => $role->id, 'userId' => $messageUserId,
                                'spaceId' => $spaceId, 'appId' => $role->appId, 'applyingRole' => $role->name);
                        }
                    }
                    $memberRoles = $currentSpace->getSpaceEngine()->getRoles(array('type' => BRole::Role_App_Member), TRUE);
                    foreach ($memberRoles as $memberRoleId => $role) {
                        if ($memberRoleId == $messageRoleId) {
                            $retJoinedUserRoles[$messageId] = array('roleId' => $role->id, 'userId' => $messageUserId,
                                'spaceId' => $spaceId, 'appId' => $role->appId, 'applyingRole' => $role->name);
                        }
                    }
                    $adminRoles = $currentSpace->getSpaceEngine()->getRoles(array('type' => BRole::Role_App_Admin), TRUE);
                    foreach ($adminRoles as $adminRoleId => $role) {
                        if ($adminRoleId == $messageRoleId) {
                            $retJoinedUserRoles[$messageId] = array('roleId' => $role->id, 'userId' => $messageUserId,
                                'spaceId' => $spaceId, 'appId' => $role->appId, 'applyingRole' => $role->name);
                        }
                    }
                }
            }
        }

        return $retJoinedUserRoles;
    }

    public function processMessage($operation, $messageId) {
        $messageStatus = 'rejected';
        $currentSpace = $this->getCurrentSpace();
        if ($operation != NULL && $messageId != NULL) {
            //check role
            $messageTable = new BMessageSheet('message');
//            foreach ($joinSpaceRequests as $messageId => $rquestTreelist) 
            {
                $messageList = $messageTable->getListById($messageId);
                $messageNameItem = $messageList->getItem('name');
                if ($messageNameItem) {
                    $messageName = $messageNameItem->getValue();
                }

                if ($messageName === 'applyJoinSpace') {
                    $messageUserIdItem = $messageList->getItem('userId');
                    if ($messageUserIdItem) {
                        $messageUserId = $messageUserIdItem->getValue();
                    }
                    $messageRoleItem = $messageList->getItem('role');
                    $messageRole = NULL;
                    if ($messageRoleItem) {
                        $messageRole = $messageRoleItem->getValue();
                    }
                    $messageRoleIdItem = $messageList->getItem('roleId');
                    if ($messageRoleIdItem) {
                        $messageRoleId = $messageRoleIdItem->getValue();
                    }
                    $messageEmailItem = $messageList->getItem('email');
                    if ($messageEmailItem) {
                        $messageEmail = $messageEmailItem->getValue();
                    }
                    $messagePasswordItem = $messageList->getItem('password');
                    if ($messagePasswordItem) {
                        $messagePassword = $messagePasswordItem->getValue();
                    }

                    if ($messageUserId != null) {
                        //get apply User
                        $applyUser = new BUser($messageUserId);

                        if ($messageRole === 'admin') {
                            $messageStatus = 'processing';
                            //get operation space & app id
                            $spaceId = $currentSpace->getId();
                            $appId = Blyn::app()->getActiveApp()->getId();
                            $customerRoles = $currentSpace->getSpaceEngine()->getRoles(array('type' => BRole::Role_App_Admin), TRUE);
                            foreach ($customerRoles as $roleId => $role) {
                                if ($appId == $role->appId) {
                                    // add role
//                                    $applyUser->addRole($roleId);
                                    $messageList->addItem('roleId', $roleId);
                                }
                            }
                        } else if ($messageRole === 'member') {
                            $messageStatus = 'processing';

                            //get operation space & app id
                            $spaceId = $currentSpace->getId();
                            $appId = Blyn::app()->getActiveApp()->getId();

                            $memberRoles = $currentSpace->getSpaceEngine()->getRoles(array('type' => BRole::Role_App_Member), TRUE);
                            foreach ($memberRoles as $memberRoleId => $role) {
                                if ($appId == $role->appId) {
                                    $messageList->addItem('roleId', $memberRoleId);
                                }
                            }
                        } else if ($messageRoleId != NULL) {
                            $messageStatus = 'processing';
                        }
                    }
                }
            }
        }

        return $messageStatus;
    }

    public function getJoinSpaceRequests($data = NULL) {
        $allowJoinRoles = $this->getAllowJoinSpaceRoles();
        $roleIdListStr = "(";
        foreach ($allowJoinRoles as $ids => $roles) {
            foreach ($roles as $id => $role)
                $roleIdListStr = $roleIdListStr . $id . ',';
        }
        $roleIdListStr = $roleIdListStr . ')';
        $roleIdListStr = str_replace(",)", ")", $roleIdListStr);
        $operation = Blyn::app()->getActiveOperation();
        $space = $this->getCurrentSpace();
        $joinSpaceRequests = array();
        $joinSpaceRequests = $operation->getMessenger()->receiveJoinSpaceMessages(NULL, $roleIdListStr, $space);

        return $joinSpaceRequests;
    }

    public function runSpaceMessage($operation = NULL, $data = NULL) {

        if (yii::app()->request->isAjaxRequest) {
            $senderControl = Blyn::app()->getUIManager()->getSenderControl();
            $updateControl = Blyn::app()->getUIManager()->getUpdateControl();
//            $senderControl = Blyn::app()->getUIManager()->getSenderControl();
            $requestItem = Blyn::app()->getUIManager()->getActiveLink()->getLinkVariable('reqId');
            $requestId = $requestItem['messageId'];

            if ($senderControl->isAjaxLinkClicked('viewMessage')) {
                $messageId = $_GET['currentMessageId'];
                $message = new BMessage($messageId);

                $ajaxView = new BUIControl();
                $ajaxView->addRenderView('manageMessage', 'manageMessage', array('messageId' => $messageId, 'message' => $message));
                $ajaxView->render();

                Blyn::app()->end();
            } else if ($senderControl->isAjaxLinkClicked('addMessage')) {
                $ajaxView = new BUIControl();
                $ajaxView->addRenderView('manageMessage', 'manageMessage', array('messageId' => '0', 'message' => null));
                $ajaxView->render();

                Blyn::app()->end();
            } else if ($senderControl->isAjaxLinkClicked('sendOperationMessage')) {
                $operation = Blyn::app()->getActiveOperation();
                $messageModel = new MessageFormModel();
                $messageModel->id = 0;
                $messageModel->sendTo = 'o[9]';
                $messageModel->messageBody = 'test operation message';

                $operation->getMessenger()->sendMessage($messageModel->messageBody, $messageModel->sendTo);

                Blyn::app()->end();
            } else if ($senderControl->isAjaxLinkClicked('sendRoleMessage')) {
                $operation = Blyn::app()->getActiveOperation();
                $messageModel = new MessageFormModel();
                $messageModel->id = 0;
                $messageModel->sendTo = 'r[41]';
                $messageModel->messageBody = 'test role message';

                $operation->getMessenger()->sendMessage($messageModel->messageBody, $messageModel->sendTo);

                Blyn::app()->end();
            } else if ($senderControl->isAjaxLinkClicked('sendMessage')) {
                $operation = Blyn::app()->getActiveOperation();
                $messageModel = new MessageFormModel();
                if (!empty($_POST) && isset($_POST['sendTo'])) {
                    $messageModel->id = 0;
                    $messageModel->sendTo = $_POST['sendTo'];
                    $messageModel->messageBody = $_POST['messageBody'];

                    $operation->getMessenger()->sendMessage($messageModel->messageBody, $messageModel->sendTo);
                }

                Blyn::app()->end();
            } else if ($senderControl->isAjaxLinkClicked('removeMessage' . $requestId)) {
                $operation = Blyn::app()->getActiveOperation();
//                $space = $this->getCurrentSpace();
                $operation->getMessenger()->removeMessageStuff($requestId);

//                Blyn::app()->end();
                $updateControl->addRenderView('spaceMessageView', 'spaceMessageView');
            }
        }
    }

    public function runManageSpace($operation = NULL, $data = NULL) {
        $sender = Blyn::app()->getUIManager()->getSenderControl();
        $updateControl = Blyn::app()->getUIManager()->getUpdateControl();
        $screen = Blyn::app()->getUIManager()->getCurrentScreen();

        $manageSpaceControl = new BUIThemedControl('manageSpace');
        $screen->addChildControl($manageSpaceControl);

        $spaceConnControl = new BUISpaceConn('spaceConn');
        $manageSpaceControl->addChildControl($spaceConnControl);

        if ($sender instanceof BUIOperation || $sender instanceof BUIScreen) {
            $manageSpaceControl->addRenderView('manageSpace_basic');
        }

        if ($sender->isAjaxLinkClicked('showManageSpace')) {
            $updateControl->addRenderView('manageSpace_basic');
        }
    }

}

?>
